package jmine.selenium;

import java.util.ArrayList;
import java.util.List;

import org.openqa.selenium.WebDriver;

/**
 * Factory responsável por instanciar {@link WebDriver}.
 * 
 * @author Rafael Volpato
 * @date Dec 8, 2010
 */
public class WebDriverFactory {

    private List<WebDriver> usedDrivers = new ArrayList<WebDriver>();

    private WebDriver webDriver;

    /**
     * @param webDriver {@link WebDriver}
     */
    public void setWebDriver(WebDriver webDriver) {
        this.webDriver = webDriver;
        this.usedDrivers.add(webDriver);
    }

    /**
     * @return a instancia de {@link WebDriver} injetada pelo Spring
     */
    public WebDriver getWebDriver() {
        return this.webDriver;
    }

    /**
     * @return uma NOVA instancia de {@link WebDriver}, do mesmo tipo que foi injetado pelo Spring.
     */
    public WebDriver getNewWebDriver() {
        try {
            WebDriver driver = this.webDriver.getClass().newInstance();
            this.usedDrivers.add(driver);
            return driver;
        } catch (InstantiationException e) {
            throw new IllegalStateException(e);
        } catch (IllegalAccessException e) {
            throw new IllegalStateException(e);
        }
    }

    /**
     * Finaliza todos os drivers inicializados por essa factory.
     */
    public void release() {
        for (WebDriver driver : this.usedDrivers) {
            driver.close();
        }
    }
}
